<?php
namespace app\admin\controller;

use think\Controller;
use think\Session;

class Login extends Controller
{
    //登录页面
    public function login()
    {
        return view('login');
    }

    //进行登录
    public function doLogin()
    {
        //获取访问者登录IP
        if(getenv('HTTP_CLIENT_IP')){
            $ip = getenv('HTTP_CLIENT_IP');
        }elseif(getenv('HTTP_X_FORWARDED_FOR')){
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        }elseif(getenv('REMOTE_ADDR')){
            $ip = getenv('REMOTE_ADDR');
        }else{
            $ip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
        }

        //获取用户输入信息
        $name = input('username');
        $pwd = md5(input('password'));
        //实例化model类查询数据库
        $res = model('Login');
        $data = $res->find($name);
        //判断用户信息是否正确
        if($data == null){
            echo "<script>window.history.go(-1);alert('账号输入错误，请重新输入')</script>";
        }else{
            if($pwd != $data['password']){
                //保存最新登录时间和IP
                $res->updateLoginInfo($data['id'],$ip,time());
                $t1 = strtotime('today');
                $t2 = strtotime('tomorrow');
                if($data['last_login_time'] >= $t1 && $data['last_login_time'] < $t2){
                    $num = $res->getLoginFalse($data['id']);
                    if($num['login_count']<5){
                        $new_num = $num['login_count'] + 1;
                        $res->updateLoginFalse($data['id'],$new_num);
                        echo "<script>window.history.go(-1);alert('密码错误，您还能输入".(5-$new_num)."次，满5次您的账号将被禁用1天')</script>";
                    }else{
                        echo "<script>window.history.go(-1);alert('密码输入错误达到5次，请联系管理员重新设置密码')</script>";
                    }
                }else{
                    $res->updateLoginFalse($data['id'],1);
                }
                echo "<script>window.history.go(-1);alert('密码输入错误！请重新输入')</script>";

            }else{
                //保存最新登录时间和IP
                $res->updateLoginInfo($data['id'],$ip,time());
                //管理员信息存入session
                Session::set('admin_login',$data);
                //跳转到首页
                $this->redirect('admin/Index/index');
            }
        }
    }

    //退出登录
    public function logout()
    {
        Session::delete('admin_login');
        $this->redirect('admin/Login/login');
    }
}